package cn.itcast.oa.base;

import cn.itcast.oa.domain.PageBean;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

@Transactional
@SuppressWarnings("unchecked")
public abstract class DaoSupportImpl<T> implements DaoSupport<T> {

	@Resource
	private SessionFactory sessionFactory;
	private Class<T> clazz;

	public DaoSupportImpl() {
		// 使用反射技术得到T的真实类型
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取当前new的对象的 泛型的父类 类型
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; // 获取第一个类型参数的真实类型
		System.out.println("clazz ---> " + clazz);
	}

	/**
	 * 获取当前可用的Session
	 * 
	 * @return
	 */
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public void save(T entity) {
		getSession().save(entity);
	}

	public void update(T entity) {
		getSession().update(entity);
	}

	public void delete(Long id) {
		Object obj = getById(id);
		if (obj != null) {
			getSession().delete(obj);
		}
	}

	public T getById(Long id) {
		if(id == null){
			return null;
		}else{
			return (T) getSession().get(clazz, id);
		}
	}

	public List<T> getByIds(Long[] ids) {
		return getSession().createQuery(//
				"FROM " + clazz.getName()+" WHERE id IN (:ids)")//
				.setParameterList("ids", ids)//
				.list();
	}

	public List<T> findAll() {
		return getSession().createQuery(//
				"FROM " + clazz.getSimpleName())//
				.list();
	}
	@Deprecated
	public PageBean getPapgeBean(int pageNum,int pageSize,String hql,List<Object> parameters){
		System.out.println("----->DaoSupportImpl.getPageBean()");
		Query listQuery = getSession().createQuery(hql);
		if(null!=parameters){
			for(int i =0 ; i<parameters.size();i++){
				listQuery.setParameter(i,parameters.get(i));
			}
		}
		listQuery.setFirstResult((pageNum-1)*pageSize);
		listQuery.setMaxResults(pageSize);
		List list = listQuery.list();
		//查询总记录数
		Query countQuery = getSession().createQuery("select count(*)"+hql);
		if (null!=parameters){
			for (int i =0;i<parameters.size();i++){
				countQuery.setParameter(i,parameters.get(i));
			}
		}
		Long count =(Long)countQuery.uniqueResult();
		return new PageBean(pageNum,pageSize,count.intValue(),list);
	}


}
